<?php
namespace Home\Controller;

class WeChatController extends HomeController {
	private $appid;
	
	function index() {
		$this->appid = $_GET['appid'];
		empty($this->appid) && exit;
		//验证消息真实性
		if ($this->init()) {
			//如果有echostr 说明是验证服务器归属权
			isset($_GET['echostr']) && exit($_GET['echostr']);
			if (IS_POST) {
				$this->msgRouter();
			}
		}
	}
	//校验signature
	private function init() {
		$signature = $_GET['signature'];
		$timestamp = $_GET['timestamp'];
		$nonce     = $_GET['nonce'];
		if (empty($signature) || empty($timestamp) || empty($nonce)) {
			return false;
		}
		static $appList;
		/* 获取缓存数据 */
		empty($appList) && $appList = S('sys_app_list');
		$key = $this->appid;
		/* 已经缓存则直接使用缓存信息 */
		if (isset($appList[$key])) {
			$token = $appList[$key];
		}else {
			$model = M('WechatApp');
			$map['id'] = $this->appid;
			$token = $model->where($map)->getField('token');
			//赋值，并添加到缓存中去
			$appList[$key] = $token;
			$count = count($appList);
			$max   = C('USER_MAX_CACHE');
			while ($count-- > $max) {
				array_shift($appList);
			}
			S('sys_app_list', $appList);
		}
		
		if (!$token) return false;
	
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode($tmpArr);
		$tmpStr = sha1($tmpStr);
	
		if($tmpStr == $signature){
			return true;
		}else{
			return false;
		}
	}
	//消息调度
	private function msgRouter() {
		//$_POST 不能识别xml数据包，所以使用 $GLOBALS["HTTP_RAW_POST_DATA"]
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		if (!empty($postStr)) {
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			//将数据对象转换为数组
			$postArr = (array)$postObj;
			//根据消息类型，分派到返回信息处理部分
			switch ($postArr['MsgType']) {
				case 'text' :
					$this->_text($postArr);
					break;
				case 'image' :
					break;
				case 'voice' :
					break;
				case 'video' :
					break;
				case 'location' :
					break;
				case 'link' :
					break;
				default : $this->_text();
			}
		}else {
			exit;
		}
	}
	
	private function _text($postArr=array()) {
		$Content          = $postArr['Content'];
		if(!empty($Content)) {
			$ToUserName   = $postArr['ToUserName'];
			$FromUserName = $postArr['FromUserName'];
			$textTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%;</CreateTime>
						<MsgType><![CDATA[text]]></MsgType>
						<Content><![CDATA[%s]]></Content>
						<FuncFlag>0</FuncFlag>
						</xml>";
			
			$responseKu = M('WechatResponse');
			$map['ask'] = array('LIKE','%'.$Content.'%');
			$contentStr = $responseKu->where($map)->getField('answer');
 			if (!$contentStr) {
				$contentStr = '不会回答这个问题啊！！！';
			}
			header('Content-Type: html/text; charset=utf-8');
			$resultStr = sprintf($textTpl, $FromUserName, $ToUserName, time() ,$contentStr);
			echo $resultStr;
		}else{
			echo "Input something...";
		}
	}
}